package design.pattern.application.specifications;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2020-05-24 14:58:00
 */
public class SpecificationsPatten02 {

    public static void main(String[] args) {
    //首先初始化一批用户
        ArrayList<User02> userList = new ArrayList<User02>();
        userList.add(new User02("苏大",3));
        userList.add(new User02("牛二",8));
        userList.add(new User02("张三",10));
        userList.add(new User02("李四",15));
        userList.add(new User02("王五",18));
        userList.add(new User02("赵六",20));
        userList.add(new User02("马七",25));
        userList.add(new User02("杨八",30));
        userList.add(new User02("侯九",35));
        userList.add(new User02("布十",40));
        //定义一个用户查询类
        IUserProvider02 userProvider = new UserProvider02(userList);
        //打印出年龄大于20岁的用户
        System.out.println("===年龄大于20岁的用户===");
        //定义一个规格书
        IUserSpecification02 userSpec = new UserByAgeThen02(20);
        for(User02 u:userProvider.findUser(userSpec)){
            System.out.println(u);
        }
    }

}
//用户类
@Data
class User02{
    private String name;
    private int age;
    public User02(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
//用户操作对象接口
interface IUserProvider02{
    //根据条件查找用户
    List<User02> findUser(IUserSpecification02 userSpecification02);
}
//规格书接口
interface IUserSpecification02{
    //是否满足要求
    boolean isSatisfiedBy(User02 user);
}
class UserByNameEq02 implements IUserSpecification02{
    private String name;
    public UserByNameEq02(String name){
        this.name = name;
    }
    @Override
    public boolean isSatisfiedBy(User02 user) {
        return user.getName().equals(name);
    }
}
class UserByAgeThen02 implements IUserSpecification02{
    private int age;
    public UserByAgeThen02(int age){
        this.age = age;
    }
    @Override
    public boolean isSatisfiedBy(User02 user) {
        return user.getAge() > age;
    }
}
class UserProvider02 implements IUserProvider02{
    private List<User02> userList = new ArrayList<>();
    public UserProvider02(List<User02> userList){
        this.userList = userList;
    }
    @Override
    public List<User02> findUser(IUserSpecification02 userSpecification02) {
        return userList.stream().filter(o -> userSpecification02.isSatisfiedBy(o)).collect(Collectors.toList());
    }
}